<?php
	/*
	 * This will be changed and converted to a class. Should work temporarily
	 */
	require_once('db_config.inc');
	register_shutdown_function('db_close_all_open_connections');
	
	$db_links_cache = array();
	
    function db_connect($host_name, $type){
    	global $db_links_cache;
    	$db_host_name = $GLOBALS['DB_CONFIG']['db'][$host_name][$type]['db_host'];
    	$db_user_name = $GLOBALS['DB_CONFIG']['db_users'][$type]['user_name'];
    	$db_password = $GLOBALS['DB_CONFIG']['db_users'][$type]['password'];
    	$schema_name = $GLOBALS['DB_CONFIG']['db'][$host_name][$type]['schema_name'];
    	
    	$db_link_address = $schema_name."_".$type;
    	
    	if(empty($db_links_cache[$db_link_address])){
    	    $db_link = mysql_connect($db_host_name, $db_user_name, $db_password, FALSE);
    		if(!$db_link){
    			print_r("No Connection to Database");
    		}	
    		else {
    	    	$db_links_cache[$db_link_address] = $db_link;
    		}
    	}
    	else {
    		$db_link = $db_links_cache[$db_link_address];
    	}
    	if(!empty($db_link)){
    		mysql_select_db($schema_name, $db_link);
    	}
    	return $db_link;
    }
    function db_query($sql, $schema_name,$type ){
    	
    	$db_link = db_connect($schema_name, $type);
    	if(!$db_link){
    		return null;
    	}
    	$result = @mysql_query($sql, $db_link);
    	if(!$result){
    		print_r("Empty result during db_query");
			//return 0;
    	}
    	return $result;
	}
	
	function db_insert_id($host_name, $type = 'write') {
		global $db_links_cache;
		$schema_name = $GLOBALS['DB_CONFIG']['db'][$host_name][$type]['schema_name'];
		$db_link_address = $schema_name."_".$type;
		
    	$db_link = $db_links_cache[$db_link_address];
    	
	    if (!is_resource($db_link)) {
	        return null;
	    }
	    $insert_id = mysql_insert_id($db_link);
	    if ($insert_id == FALSE || $insert_id == 0) {
	        return null;
	    }
	    return $insert_id;
	}
	
	function db_close_all_open_connections(){
	    global $db_links_cache;
	    foreach($db_links_cache as $db_link){
			if (is_resource($db_link)) {
	            @mysql_close($db_link);
	        }
	    }
	}
    // This is used for getting one row
	function db_get_row($qhandle) {
        return mysql_fetch_array($qhandle, MYSQL_ASSOC);
    }
    
    
    // Getting each row one at a time
    function db_get_row_array($qhandle) {
        return mysql_fetch_array($qhandle);
    }
    
	// Get everyting 
    function db_get_all_rows($qhandle) {
    	$rows = array();
        while ($row = db_get_row_array($qhandle)) {
            $rows[] = $row;
        }
    	return $rows;
	}
	function db_num_rows($result) {
    	return (mysql_num_rows($result));
	}
	
	
	
?>
